package com.xuyuan.json.jackson;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;

import java.util.Date;

public class JacksonTest1 {
    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        Person person = new Person();
        person.setAge(25);
        person.setDate(new Date());
        person.setName("xuyuan");
        person.setHeight(178);

        /* 序列化 */
        String jsonString = objectMapper.writeValueAsString(person);
        System.out.println(jsonString);
        //{"myHeight":178,"birthday":"2024-08-27 11:00:32","myAge":25,"myName":"xuyuan"}
        /* 反序列化 */
        Person newPerson = objectMapper.readValue(jsonString, Person.class);
        System.out.println(newPerson);
        // Person(name=xuyuan, age=25, date=Tue Aug 27 19:00:32 CST 2024, height=178)
        /* 对象转换 */
        Animal animal = objectMapper.convertValue(person, Animal.class);
        System.out.println(animal);
        // Animal(field1=xuyuan, field2=25, field3=Tue Aug 27 19:00:32 CST 2024, field4=178)
    }

    @Data
    static class Person {
        @JsonProperty(value = "myName", index = 4)
        private String name;
        @JsonProperty(value = "myAge", index = 3)
        private Integer age;

        @JsonProperty(value = "birthday", index = 2)
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        @JsonInclude(JsonInclude.Include.NON_NULL)
        private Date date;
        @JsonProperty(value = "myHeight", index = 1)
        private int height;
    }

    @Data
    static class Animal {
        @JsonProperty("myName")
        private String field1;
        @JsonProperty("myAge")
        private Integer field2;

        @JsonProperty("birthday")
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private Date field3;
        @JsonProperty("myHeight")
        private int field4;
    }
}

